package com.hqd.jjvm.jnative.reflect;

import com.hqd.jjvm.jnative.JNativeRegistry;
import com.hqd.jjvm.rtda.JThread;
import com.hqd.jjvm.rtda.LocalVars;
import com.hqd.jjvm.rtda.StackFrame;
import com.hqd.jjvm.rtda.heap.JClass;
import com.hqd.jjvm.rtda.obj.JObject;

public class JReflectionNativeRegistry extends JNativeRegistry {
    private static final JReflectionNativeRegistry instance = new JReflectionNativeRegistry();
    protected static final String CLASS_PATH = "sun/reflect/Reflection";

    static {
        registry(CLASS_PATH, "getCallerClass", "()Ljava/lang/Class;", JReflectionNativeRegistry::getCallerClass);
        registry(CLASS_PATH, "getClassAccessFlags", "(Ljava/lang/Class;)I", JReflectionNativeRegistry::getClassAccessFlags);

    }

    protected static void getCallerClass(JThread jThread) {
        StackFrame stackFrame = jThread.getJvmStack().get(2);
        JObject ref = stackFrame.getJMethod().getJClass().getJObject();
        jThread.getJvmStack().pushOperandStackRefVal(ref);
    }

    protected static void getClassAccessFlags(JThread jThread) {
        LocalVars localVars = jThread.getJvmStack().getTop().getLocalVars();
        JObject ref = localVars.getRefVal(0);
        JClass goClass = ref.getJClass();
        Integer flags = goClass.getAccessFlags();
        jThread.getJvmStack().pushOperandStackIntVal(flags);
    }

    public static JReflectionNativeRegistry getInstance() {
        return instance;
    }
}
